<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" size="small">
        <el-form-item>
          <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                          :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="timeListArray()"></el-date-picker>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">生成新短链接</el-button>
      </el-form>
      <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
        </el-table-column>
        <el-table-column align="center" label="短链接" prop="short_connection"></el-table-column>
        <el-table-column align="center" label="原始链接">
          <template slot-scope="scope">
            <div class="longlinks">{{scope.row.long_connection}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="生成时间" prop="datetime"></el-table-column>
        <el-table-column align="center" label='操作' width="330">
          <template slot-scope="scope">
            <el-button  type="primary" plain size="mini" class="tag-read" :data-clipboard-text="scope.row.short_connection"  @click="copyLink(1)">复制短链</el-button>
            <el-button  type="primary" plain size="mini" class="tag-read" :data-clipboard-text="scope.row.long_connection"  @click="copyLink(1)">复制长链</el-button>
            <el-button  type="primary" plain size="mini" @click="deleteLinks(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <el-dialog  title="生成短链接" :visible.sync="addTypeDialog" width="550px">
      <div class="main">
        <el-form>
          <el-form-item>
            <el-input type="textarea" class="textarea" show-word-limit v-model="formdialog.longlinks" @input="textareaLength" :disabled="formdialog.shortlink!=''" placeholder="请输入长链接，最多150个字符，不能包含有空格" :maxlength="textarealengths"></el-input>
          </el-form-item>
        </el-form>
        <div class="main_botton">
          <span>短链：{{formdialog.shortlink}}</span>
          <el-button  type="primary" plain v-if="!formdialog.shortlink" @click="createShortLink()">生成</el-button>
          <el-button  type="primary" class="tag-read" plain v-else :data-clipboard-text="formdialog.shortlink" @click="copyLink(2)">复制</el-button>
        </div>
        <div class="main_botton">
          <span></span>
          <el-button  type="primary" plain @click="closeDialoig()">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                     layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import {
  getLinkInfo,
  getLinkInfoPage,
  createLink,
  deleteLink
} from "@/api/operation/shortLink";
import {
  pickerOptionsF,
  pickerDateDot,
} from "@/utils";
import Clipboard from 'clipboard';
import {
  linkName
} from "@/utils/validate";
export default {
  name: 'shortLink',
  data(){
    return{
      list: null,  //数据
      links:"",  //短连接域名
      listLoading: false,  //表格换场动画
      addTypeDialog: false, // 弹窗是否显示
      pickerOptions: pickerOptionsF(),
      pickerDate: null,
      formInline: {  //开始时间，结束时间
        begin_time: "",
        end_time: "",
      },
      textarealengths:150, //链接长度
      currentPage: 1,
      totalDataNumber: 0,
      formdialog:{  //弹框中的长短链接
        longlinks:"",
        shortlink:""
      }
    }
  },
  mounted() {
    this.links = location.host.split(':')[0] == 'localhost' ? `http://${location.host}/#/w/` : `https://${location.host}/sms/#/w/`;
    this.listArray();
  },
  methods:{
    listArray(){  //获取数据
      this.listLoading = true;
      this.list = [];
      getLinkInfoPage(this.formInline).then(response=>{
        this.totalDataNumber = response.count / 1;
        if (this.totalDataNumber == 0) {
          this.listLoading = false;
        } else {
          getLinkInfo(this.formInline).then(res=>{
            this.list = res.map(val=>{
              val.short_connection= this.links+ val.short_connection;
              return val
            });
            this.listLoading = false;
          });
        }
      });
    },
    timeListArray(){  //时间选择
      this.formInline.begin_time=this.pickerDate[0];
      this.formInline.end_time=this.pickerDate[1];
      this.listArray();
    },
    deleteLinks(arrAy){
      this.$confirm(
          "链接删除后不可恢复，是否确定删除？",
          "提示",
          { type: "warning" }
      ).then(() => {
        deleteLink({id:arrAy.id}).then(res=>{
          if(res.code==1){
            this.listArray();
            this.$message.success("删除成功");
          }
        })
      });
    },
    createShortLink(){  //生成
      if(this.formdialog.longlinks==""){
        this.$message.error('请先填写长链接，在进行生成！');
        return ;
      }
      if(!linkName(this.formdialog.longlinks)){
        this.$message.error('请填正确的长链接！');
        return ;
      }
      createLink({url:this.formdialog.longlinks}).then(res=>{
        if(res.code==1){
          this.$message.success("短链接生成成功");
          this.listArray();
          this.formdialog.shortlink=this.links+res.short_connection;
        }
      });
    },
    copyLink(type){  //复制
      let clipboard = new Clipboard('.tag-read');
      if(this.formdialog.shortlink=="" && type==2){
        this.$message.error('请先生成短连接，在进行复制！');
        return ;
      }
      clipboard.on('success', e => {
        this.$message.success("复制成功");
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        this.$message.error('该浏览器不支持!');
        // 释放内存
        clipboard.destroy()
      })
    },
    handleCurrentChange(val) {  //获取某个分页的数据
      this.listLoading = true;
      getLinkInfo(this.formInline,val).then(res=>{
        this.list = res.map(val=>{
          val.short_connection= this.links+ val.short_connection;
          return val
        });
        this.listLoading = false;
      }).catch(res => {
        this.listLoading = false;
      });
    },
    textareaLength(){
      if(this.formdialog.longlinks.length>=this.textarealengths){
        this.$message.error('链接长度超出！');
      }
    },
    addTypeClick() {
      this.formdialog.longlinks="";
      this.formdialog.shortlink="";
      this.addTypeDialog = true;
    },
    closeDialoig(){
      this.addTypeDialog = false;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.customContainer {
  overflow-y: auto;
}
.longlinks{
  display:-webkit-box;
  text-overflow:ellipsis;
  overflow:hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient:vertical;
}
.main{
  .main_botton{
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    button{
      width: 100px;
      height: 35px;
      line-height: 10px;
    }
  }
}
</style>
